#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :2.0.9 多任务文件夹copy.py
# @Time      :2020/7/14 16:23
# @Author    :亮亮
# @说明       :多任务复制文件夹
# @总结       :
import os
import time
import multiprocessing


def copy_file(q, file_name, old_folder_name, new_folder_name):
    """
    复制文件夹
    :param file_name: 要复制的文件名
    :param old_folder_name: 老文件夹名
    :param new_folder_name: 新文件夹名
    :return:
    """

    # 打开读取旧文件
    with open(old_folder_name + "/" + file_name, "rb") as old_f:
        content = old_f.read()

    # 写入新文件
    with open(new_folder_name + "/" + file_name, "wb") as new_f:
        new_f.write(content)

    # 拷贝完，向队列中放入一个消息
    q.put(file_name)


def main():
    # 1.获取用户想要复制文件夹的名字
    old_folder_name = input("输入要复制文件夹的名字：")

    # 2.创建新的文件夹（若名字相同抛出异常）
    try:
        new_folder_name = old_folder_name + "[附件]"
        os.mkdir(new_folder_name)
    except:
        pass

    # 3.获取该文件夹下文件的名字
    file_names = os.listdir(old_folder_name)

    # 4.创建进程池
    po = multiprocessing.Pool(5)

    # 5.创建一个队列
    q = multiprocessing.Manager().Queue()

    # 6.向程池中添加复制文件的任务
    for file_name in file_names:
        po.apply_async(copy_file, args=(q, file_name, old_folder_name, new_folder_name))

    # 6.关闭进程池，等待子进程完毕
    po.close()

    # 7.显示拷贝进度
    copy_all_num = len(file_names)
    copy_ok_num = 0
    while True:
        copy_name = q.get()

        # 累加
        copy_ok_num += 1

        # \r将光标的位置退回到本行开头
        print("\r----已经完成：{:.0f} % ----".format(copy_ok_num*100/copy_all_num), end="")

        if copy_ok_num >= copy_all_num:
            break


if __name__ == '__main__':
    main()
